package com.kehutong.charge.admin;

import com.kehutong.charge.entity.ChargeLadderConfig;
import com.kehutong.charge.entity.ChargeProjectConfig;
import com.kehutong.charge.entity.ChargeTypeConfig;
import com.kehutong.charge.service.ChargeProjectService;
import com.kehutong.charge.util.enums.ChargeCalcEnum;
import com.kehutong.charge.util.enums.ChargeFeeEnum;
import com.kehutong.charge.util.enums.DateUnitEnum;
import com.kehutong.charge.util.enums.PriceUnitEnum;
import com.kehutong.common.DeptService;
import com.kehutong.common.dto.DeptDTO;
import com.kehutong.common.util.Token;
import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.EnumUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @program: kht
 * @description: 收费项目管理
 * @author: joneron
 * @create: 2021/6/21
 **/
@MvcAction
@ReqMapping("/admin/pay/charge/project")
public class ChargeProjectController {

    private static final Logger logger = LoggerFactory.getLogger(ChargeProjectController.class);

    @Inject
    DeptService deptService;

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    ChargeProjectService chargeProjectService;

    @ReqMapping("/page")
    @HasPermission("pay:charge:type:view")
    public Object page(JSONObject jsonObject) {
        return chargeProjectService.findPage(jsonObject);
    }

    @ReqMapping("/list")
    @HasPermission("pay:charge:type:view")
    public Object list(JSONObject jsonObject) {
        return chargeProjectService.findList(jsonObject);
    }

    @HasPermission("pay:charge:type:edit")
    @ReqMapping("/save")
    public Object save(JSONObject jsonObject,Token token) throws Exception {

        setObj(jsonObject,token,null,true);

        return Result.success();
    }

    //@Bean(copy=true)
    @HasPermission("pay:charge:type:edit")
    @ReqMapping("/update")
    public Object update(JSONObject jsonObject,Token token,ChargeProjectConfig config) throws Exception {

        setObj(jsonObject,token,config,false);

        return Result.success();
    }

    private void setObj(JSONObject jsonObject, Token token,ChargeProjectConfig entity,boolean bool) throws Exception {

        if(bool){ //如果是添加則重置對象
            entity = Pool.newInstance(ChargeProjectConfig.class);
        }

        JSONArray ladderList = jsonObject.getJSONArray("ladderList");
        List<ChargeLadderConfig> configList = new LinkedList<>();
        for (int i = 0; i < ladderList.size(); i++) {
            JSONObject json = ladderList.getJSONObject(i);
            ChargeLadderConfig config = Pool.newInstance(ChargeLadderConfig.class);
            config.setChargeProjectNo(entity.getId());
            config.setUsageType(json.getString("usageType"));
            config.setUsagePrice(json.getBigDecimal("usagePrice"));
            config.setUsageStart(json.getBigDecimal("usageStart"));
            config.setUsageEnd(json.getBigDecimal("usageEnd"));
            config.setCreateName(token.getUsername());

            configList.add(config);
        }

        List<String> departList = token.getDepartments();
        if(null != departList && departList.size() > 0){
            logger.error("用户{}数据异常，部门为空！",token.getUsername());
            DeptDTO deptDTO = deptService.getDept(departList.get(0));
            entity.setDepartmentNo(deptDTO.getDepartmentNo());
            entity.setDepartmentNos(deptDTO.getDepartmentNos());
            entity.setDepartmentName(deptDTO.getDepartmentName());
        }
        entity.setPrice(jsonObject.getBigDecimal("price"));
        entity.setProjectFeeName(jsonObject.getString("projectFeeName"));
        entity.setLadderList(configList);
        entity.setCreateName(token.getUsername());
        entity.setFeeTypeNo(jsonObject.getString("feeTypeNo"));
        entity.setFeeTypeName(jsonObject.getString("feeTypeName"));
        Boolean guarantee = jsonObject.getBoolean("guarantee");
        entity.setGuarantee(Objects.isNull(guarantee)?false:guarantee);
        entity.setCommunityNo(jsonObject.getString("communityNo"));
        entity.setCommunityName(jsonObject.getString("communityName"));
        Boolean invoice = jsonObject.getBoolean("invoice");
        entity.setInvoice(Objects.isNull(invoice)?false:invoice);
        entity.setInvoiceRax(jsonObject.getInteger("invoiceRax"));
        Boolean lateFee = jsonObject.getBoolean("lateFee");
        entity.setLateFee(Objects.isNull(lateFee)?false:lateFee);
        entity.setLateFeeNum(jsonObject.getInteger("lateFeeNum"));
        entity.setStatus(true);

        JSONObject obj1 = jsonObject.getJSONObject("lateFeeScale");
        if(null != obj1){
            entity.setLateFeeScale(EnumUtil.getEnum(PriceUnitEnum.class,obj1.getString("id")));
        }
        String obj2 = jsonObject.getString("lateFeeUnit");
        if(!org.coraframework.util.Objects.isBlank(obj2)){
            entity.setLateFeeUnit(EnumUtil.getEnum(DateUnitEnum.class,obj2));
        }
        JSONObject obj3 = jsonObject.getJSONObject("feeEnum");
        if(null != obj3){
            entity.setFeeEnum(EnumUtil.getEnum(ChargeFeeEnum.class, obj3.getString("id")));
        }
        JSONObject obj4 = jsonObject.getJSONObject("calcEnum");
        if(null != obj4){
            entity.setCalcEnum(EnumUtil.getEnum(ChargeCalcEnum.class,obj4.getString("id")));
        }

        entity.setUsageEnd(jsonObject.getBigDecimal("usageEnd"));
        entity.setUsageStart(jsonObject.getBigDecimal("usageStart"));
        entity.setUsagePrice(jsonObject.getBigDecimal("usagePrice"));

        if(bool){
            chargeProjectService.save(entity);
        }else{
            chargeProjectService.update(entity);
        }
    }

    @HasPermission("pay:charge:type:edit")
    @ReqMapping("/delete")
    public Object delete(ChargeProjectConfig entity) {

        return chargeProjectService.deleteById(entity.getId());
    }

    @ReqMapping("/get")
    public Object get(ChargeProjectConfig entity) {

        List<ChargeLadderConfig> configList = jdbcSession.findArray(ChargeLadderConfig.class)
                .eq("chargeProjectNo",entity.getId())
                .order("usageStart","asc").exe();
        entity.setLadderList(configList);

        return Result.success(entity);
    }

    @ReqMapping("/setStatus")
    @HasPermission("pay:charge:type:edit")
    public Object setStatus(ChargeProjectConfig entity) throws Exception {
        entity.setStatus(!entity.isStatus());
        jdbcSession.updateById(entity);
        return Result.success();
    }


    /**
     * 获取指定小区和收费类型的收费配置
     * @param jsonObject
     * @return
     */
    @ReqMapping("/get/config")
    public Object getConfig(JSONObject jsonObject) {
        return chargeProjectService.getConfig(jsonObject);
    }

}
